﻿using QDPay.Bus;
using QDPay.Bus.domain.WxStore;
using QDPay.code;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace QDPay
{
    public partial class frmLogin : FormBase
    {
        WxStores store = new WxStores();
        public frmLogin()
        {
            InitializeComponent();
            lblMsg.Text = "";
            txtPwd.PasswordChar = '*';
        }
        private void frmLogin_Load(object sender, EventArgs e)
        {
            WxStores.InitPcKey();
        }
        private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseForm(this);
        }

        private void frmLogin_KeyPress(object sender, KeyPressEventArgs e)
        {
            int key = (int)e.KeyChar;
            if (key == 13)
            {
                btnLogin_Click(sender, e);
            }
        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            if (txtUserName.Text.Trim() == "")
            {
                txtUserName.Focus();
                return;
            }
            if (txtPwd.Text.Trim() == "")
            {
                txtPwd.Focus();
                return;
            }
            btnLogin.Enabled = false;
            Login();
            btnLogin.Enabled = true;
        }

        void Login()
        {
            var json = store.Login(txtUserName.Text, txtPwd.Text);
            if (json.Code > 0)
            {
                Echo(json.Message);
                return;
            }
            if (json.Data == null)
            {
                Echo("登录失败,请联系您的服务商");
                return;
            }

            Session.StoreEmployee = new WxStoreEmployee()
            {
                Id = json.Data.Id,
                Name = json.Data.Name,
                CreateUid = json.Data.CreateUid,
                LoginName = json.Data.LoginName,
                StoreName = json.Data.StoreName
            };
            CloseForm(this);
            Close();
        }

        void RunWorkerThread(object state)
        {
            Echo(state.ToString());
        }
        void Echo(string msg)
        {
            if (lblMsg.InvokeRequired)
            {
                lblMsg.Invoke((MethodInvoker)delegate
               {
                   lblMsg.Text = msg;
               });
            }
            else
                lblMsg.Text = msg;
        }
    }
}
